package com.burgeon.backend.EnterpriseWeChat.service.Impl;


import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.modEmployeeIsInvite;
import com.burgeon.backend.EnterpriseWeChat.rest.QueryErpEmpData;
import com.burgeon.backend.EnterpriseWeChat.rest.QueryErpEmpDataByIDs;
import com.burgeon.backend.EnterpriseWeChat.rest.wx.FindVIPDataByWCcode;
import com.burgeon.backend.EnterpriseWeChat.rest.wx.UpVIP_EXID;
import com.burgeon.backend.EnterpriseWeChat.service.EWBackendService;
import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.EnterpriseWeChat.service.ex.ErrorDataException;
import com.burgeon.backend.EnterpriseWeChat.utils.WXBizMsgCrypt;
import com.burgeon.backend.SHOP.entity.EmpData;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.*;

@Service
public class EWBackendServiceImpl implements EWBackendService {
    @Autowired
    private EWInfoService ewInfoService;
    @Autowired
    private AccountMapper accountMapper;


    /**
     * 生成 指定员工企业微信
     * @param account
     */
    @Override
    public void MassProductionEWEmp(String account,String[] arr) throws ErrorDataException{

        if (null==arr||arr.length < 1){
            throw new ErrorDataException("未选择导购");
        }

        System.err.println(Arrays.toString(arr));
        Info info = GetInfo(account);

        QueryErpEmpDataByIDs queryErpEmpData = new QueryErpEmpDataByIDs(info.getUrl(), info.getAccount(), info.getPassword());
        modEmployeeIsInvite modEmployeeIsInvite = new modEmployeeIsInvite(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            ArrayList<EmpData> data = queryErpEmpData.getData(arr);
            System.err.println(data);
            for (EmpData empData :data){
                ewInfoService.createEWEmp(empData.getCode(),empData.getName(),empData.getPhone(),account);
                //修改为已邀约
                modEmployeeIsInvite.getData(empData.getId(),"Y");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }

    }






    /**
     * 生成 全部员工企业微信
     * @param account
     */
    @Override
    public void MassProductionEWEmpAll(String account) throws ErrorDataException {
        Info info = GetInfo(account);

        QueryErpEmpData queryErpEmpData = new QueryErpEmpData(info.getUrl(), info.getAccount(), info.getPassword());
        modEmployeeIsInvite modEmployeeIsInvite = new modEmployeeIsInvite(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            ArrayList<EmpData> data = queryErpEmpData.getData();
            for (EmpData empData :data){
                ewInfoService.createEWEmp(empData.getCode(),empData.getName(),empData.getPhone(),account);
                //修改为已邀约
                modEmployeeIsInvite.getData(empData.getId(),"Y");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }



    //接收事件
    @Override
    public void WXSaaSCallback(HttpServletRequest req, ServletResponse res,
                               String CORP_ID, String SUITE_TOKEN,
                               String SUITE_ENCODING_AES_KEY, String msgSignature,
                               String timestamp, String nonce, String echostr,
                               String token) {
        String postData = null;
        try {
            InputStream inputStream = req.getInputStream();
            postData = IOUtils.toString(inputStream, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result;

        try {
            //=======验证回调url有效性=======
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(SUITE_TOKEN,
                    SUITE_ENCODING_AES_KEY, CORP_ID);//注意是CORP_ID
            if (null != echostr) {
                result = wxBizMsgCrypt.VerifyURL(msgSignature, timestamp, nonce, echostr);
                System.err.println(result);
                res.getWriter().write(result);    //对echostr参数解密并原样返回echostr明文(不能加引号，不能带bom头，不能带换行符)
                return;
            }

            String a = wxBizMsgCrypt.DecryptMsg(msgSignature, timestamp, nonce, postData);
            System.err.println("******************************************");
            System.err.println(a);
            System.err.println("******************************************");
            Map<String, String> map = convertToMap(a);

            if (!"add_external_contact".equals(map.get("ChangeType"))){
                return;
            }

            String nickName = WEClientItem(map.get("ExternalUserID"),token);


            //匹配微信码 写入exid
            Info info = GetInfo(token);
            FindVIPDataByWCcode findVIPDataByWCcode = new FindVIPDataByWCcode(info.getUrl(), info.getAccount(), info.getPassword());

            String ID = findVIPDataByWCcode.getData(nickName);
            if (null != ID){
                UpVIP_EXID upVIPExid = new UpVIP_EXID(info.getUrl(), info.getAccount(), info.getPassword());
                upVIPExid.getData(ID,map.get("ExternalUserID"));
            }



            //HashMap external = new HashMap();
            //external.put("external_userid",map.get("ExternalUserID"));

            //获取企业微信openid
            /*String accessToken = ewInfoService.contactMeAccessToken(token);
            String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/convert_to_openid?" +
                    "access_token="+accessToken;
            RestTemplate restTemplate = new RestTemplate();
            String str = restTemplate.postForObject(url,external ,String.class);
            System.err.println(str);
            System.err.println("******************************************");*/


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //客户详情
    public String WEClientItem(String externalUserID,String token){

        String accessToken = ewInfoService.contactMeAccessToken(token);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?" +
                "access_token=" + accessToken +
                "&external_userid="+externalUserID;
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.getForObject(url, String.class);
        System.err.println(str);
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject external_contact = jsonObject.getJSONObject("external_contact");
            String name = external_contact.getString("name");
            System.err.println(name);

            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(name.getBytes());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

    public static void main(String[] args) {

        String a = "ASd是多大(*&@&";
        System.err.println(strConvertBase(a));
    }
    public static String strConvertBase(String str) {
        if(null != str){
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(str.getBytes());
        }
        return null;
    }
    /**
     * 转换简单的xml to map
     *
     * @param xml xml
     * @return map
     */
    private static Map<String, String> convertToMap(String xml) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xml);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            if (root != null) {
                NodeList childNodes = root.getChildNodes();
                if (childNodes != null && childNodes.getLength() > 0) {
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node node = childNodes.item(i);
                        if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                            map.put(node.getNodeName(), node.getTextContent());
                        }
                    }
                }
            }
        } catch (DOMException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
